package org.voyager.service.wx.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.voyager.service.wx.common.dict.RedisKey;
import org.voyager.service.wx.dao.MpAccountDao;
import org.voyager.service.wx.domain.MpAccountPO;
import org.voyager.service.wx.model.AccountBO;
import org.voyager.service.wx.service.AccountService;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 功能说明: <br>
 * 系统说明: <br>
 * 模块说明: <br>
 * 功能描述: <br>
 * <br>
 */
@Service
public class AccountServiceImpl implements AccountService {

    final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MpAccountDao accountDao;
    @Autowired
    StringRedisTemplate redisTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void refreshShareStore() {
        Map<String, AccountBO> accountsMap = new HashMap<>();
        accountDao.queryAll()
                .stream()
                .filter(MpAccountPO::getEnabled)
                .forEach(po -> {
                    AccountBO bo = new AccountBO();
                    BeanUtils.copyProperties(po, bo);
                    accountsMap.put(bo.getPublicKey(), bo);
                });
        // 找出所有的已失效KEY 并删除
        Set<String> keys = redisTemplate.<String, String>opsForHash().keys(RedisKey.ACCOUNTS_PREFIX);
        keys.stream()
                .filter(key -> !accountsMap.containsKey(key))
                .forEach(key -> {
                    redisTemplate.opsForHash().delete(RedisKey.ACCOUNTS_PREFIX, key);
                });
        // 更新加载所有的账号
        accountsMap.entrySet()
                .stream()
                .forEach(entry -> {
                    try {
                        redisTemplate.<String, String>opsForHash()
                                .put(RedisKey.ACCOUNTS_PREFIX, entry.getKey(), objectMapper.writeValueAsString(entry.getValue()));
                    } catch (Exception e) {
                        LOGGER.warn("[AccountService.refreshShareStore] missing an entry => {}", entry.getKey(), e);
                    }
                });
    }
}
